<?php
/*
 * 商品列表
 */
namespace app\admin\controller;
use app\common\controller\AdminBase;
use think\facade\Db;
use think\facade\Session;
use app\common\model\Goods as GoodsModel;
use app\common\model\Sku;
use app\common\model\GoodSku;

class Goods extends AdminBase
{
    public function lists()
    {
        $param = $this->request->param();
        if (!empty($param['title'])) {
            $where = function ($query) use ($param){$query->where('name','LIKE', '%'.trim($param['title']).'%');};
        }else{
            $where = 1;
        }
        $list = GoodsModel::with('cate')->where($where)->order('id','DESC')->paginate();
        foreach ($list as $key => $v) {
            $list[$key]['img'] = json_decode($v['img']);
        }
        return $this->fetch('index',['list'=>$list]);
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            //验证规则
            $verify = input('_verify', true);
            if($verify!='0'){
                try{
                    $this->validate($param, 'goods');
                }catch (\Exception $e){
                    $this->error($e->getMessage());
                }
            }
            $param['img'] = json_encode($param['img']);//图片转json
            if (!empty($param['sku_id'])) {
                is_array($param['sku_id']) && $param['sku_id'] = implode(',',$param['sku_id']);
            }
            $result = GoodsModel::create($param);
            !$result && $this->error($this->errorMsg);
            insert_admin_log('添加了商品');
            $this->success('添加成功');
        }
        $cate = Db::table('good_cate')->where('status',1)->select()->toArray();
        $data = list_to_tree($cate);
        return $this->fetch('save',[
            'group'=>Db::table('good_group')->where('status',1)->select(),
            'cate'=>$data,
            'sup'=>Db::table('supplier')->where('status',1)->select(),
        ]);
    }

    public function edit()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            //验证规则
            $verify = input('_verify', true);
            if($verify!='0'){
                try{
                    $this->validate($param, 'goods');
                }catch (\Exception $e){
                    $this->error($e->getMessage());
                }
            }
            $param['img'] && $param['img'] = json_encode($param['img']);//图片转json
            if (!empty($param['sku_id'])) {
                is_array($param['sku_id']) && $param['sku_id'] = implode(',',$param['sku_id']);
            }
            $result = GoodsModel::update($param);
            !$result && $this->error($this->errorMsg);
            insert_admin_log('修改了商品');
            $this->success('修改成功');
        }
        $data = GoodsModel::where('id',input('id'))->find();
        $data['img'] = json_decode($data['img']);
        $sku = [];
        $data['group_id'] && $sku = Sku::field('id,name')->whereIn('pid',Db::table('good_group')->where(['id'=>$data['group_id'],'status'=>1])->value('sku_id'))->select();
        $cate = Db::table('good_cate')->where('status',1)->select()->toArray();
        $cateData = list_to_tree($cate);
        return $this->fetch('save',[
            'group'=> Db::table('good_group')->where('status',1)->select(),//模型
            'cate'=> $cateData,//分类
            'sup'=> Db::table('supplier')->where('status',1)->select(),//供应商
            'data' => $data,//商品信息
            'sku' => $sku,//商品规格
        ]);
    }

    public function status()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            //验证规则
            $verify = input('_verify', true);
            if($verify!='0'){
                try{
                    $this->validate($param, 'goods');
                }catch (\Exception $e){
                    $this->error($e->getMessage());
                }
            }
            $result = GoodsModel::update($param);
            !$result && $this->error($this->errorMsg);
            insert_admin_log('修改了商品');
            $this->success('修改成功');
        }
    }

    //动态获取商品
    public function sku_list()
    {
        if ($this->request->isPost()) {
            $id = $this->request->param('id');
            $sku = Sku::field('id,name')->whereIn('pid',Db::table('good_group')->where(['id'=>$id,'status'=>1])->value('sku_id'))->select()->toArray();
            $ret = '';
            foreach ($sku as $key => $v) {
                $ret .= "<input type='checkbox' name='sku_id[]'  value=".$v['id']." title=".$v['name'].">";
                $ret .= "<div class='layui-unselect layui-form-checkbox'><span>".$v['name']."</span><i class='layui-icon layui-icon-ok'></i></div>";
            }
            return $ret;
        }
    }
    //多规格
    public function sku()
    {
        $gid = input('id');
        if ($this->request->isPost()) {
            //编辑修改
            $param = $this->request->param();
            $g_id = $param['id'];
            // dump($param);
            $data = array_keys($param);//根据键生成新数组
            array_splice($data,array_search('id',$data),1);//删除数组下值为ID的数据
            $result = Db::table('good_sku')->where('good_id',$g_id)->column('sku');
            foreach ($result as $key => $v) {
                if (!in_array($v,$data)) {
                    $id = Db::table('good_sku')->where(['good_id'=>$g_id,'sku'=>$v])->column('id');
                    GoodSku::destroy($id);
                }
            }
            foreach ($data as $key => $v) {
                if (!in_array($v,$result)) {
                    $param[$v]['good_id'] = $g_id;
                    $param[$v]['sku'] = $v;
                    GoodSku::create($param[$v]);
                }else{
                    $id = Db::table('good_sku')->where(['good_id'=>$g_id,'sku'=>$v])->value('id');
                    GoodSku::where('id',$id)->update($param[$v]);
                }
            }
            echo json_encode(['code'=>1,'msg'=>'更新成功']);exit;
        }
        $group_id = explode(',',Db::table('good_group')->where('id',GoodsModel::where('id',$gid)->value('group_id'))->value('sku_id'));
        foreach ($group_id as $v) {
            if (Sku::where('pid',$v)->count()) {
                $name = Sku::where('id',$v)->value('name');
                $sku[$name] =Sku::where('pid',$v)->column('name','id');
                // $vs[] = $v;
            }
        }
        $g_sku = GoodsModel::where('id',$gid)->value('sku_id');//商品列表选中属性
        $rs = Db::table('good_sku')->field('sku,sku_price,sku_stock')->where('good_id',$gid)->select()->toArray();
        $goodsku = [];
        if ($rs) {
            for ($i=0; $i <count($rs) ; $i++) {
                $key =$rs[$i]['sku'];
                $sku_price = $rs[$i]['sku_price'];
                $sku_stock = $rs[$i]['sku_stock'];
                $goodsku[$key] = [
                    'sku_price' =>$sku_price,
                    'sku_stock' =>$sku_stock,
                ];
            }
        }
        return $this->fetch('sku',[
            'sku'=>$sku,
            'g_sku'=>$g_sku,
            'goodsku'=>json_encode($goodsku),
            // 'name'=>$vs
        ]);
    }

    public function del()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            Db::table('good_sku')->where('good_id',$param['id'])->find() && $this->error('商品存在多规格属性，无法删除');
            GoodsModel::destroy($param['id']);
            Db::table('good_sku')->where('good_id',$param['id'])->update(['delete_time'=>time()]);    //删除商品多规格属性
            insert_admin_log('删除了商品');
            $this->success('删除成功');
        }
    }

}